﻿using System;
using System.Collections.Generic;
using System.Text;

using System.Data;

using ISS.CaseStudy.DAL;
using ISS.CaseStudy.Entities;

namespace ISS.CaseStudy.BLL
{
    public class TechnologyBLL
    {
        public static DataSet GetAll()
        {
            return TechnologyDLL.GetAllInfos();
        }

        public static TechnologyInfo GetInfo(string id)
        {
            return TechnologyDLL.GetInfo(id);
        }

        public static bool Update(TechnologyInfo technologyInfo, out string message)
        {
            message = string.Empty;

            DataSet dataSet = TechnologyDLL.GetAllInfos();
            foreach (DataRow row in dataSet.Tables[0].Rows)
            {
                if (technologyInfo.Value.Equals(row["Value"].ToString()) &&
                    (!technologyInfo.Id.Equals(row["Id"].ToString())))
                {
                    message = "The technology type already existed!";
                    return false;
                }
            }

            return TechnologyDLL.Update(technologyInfo);
        }

        public static bool Insert(TechnologyInfo technologyInfo, out string message)
        {
            message = string.Empty;

            DataSet dataSet = TechnologyDLL.GetAllInfos();
            foreach (DataRow row in dataSet.Tables[0].Rows)
            {
                if (technologyInfo.Value.Equals(row["Value"].ToString()))
                {
                    message = "The technology type already existed!";
                    return false;
                }
            }

            return TechnologyDLL.Insert(technologyInfo);
        }

        public static bool Delete(string id)
        {
            DataSet dataSet = CaseStudyDLL.GetAllInfos(string.Empty, true);
            foreach (DataRow row in dataSet.Tables[0].Rows)
            {
                string tech = row["Technology"].ToString();
                string[] ss = tech.Split(new char[] { ';' });
                bool flag = false;

                foreach (string s in ss)
                {
                    if (s.Equals(id))
                    {
                        flag = true;
                        break;
                    }
                }

                if (flag == true)
                {
                    string tempStr = string.Empty;
                    foreach (string s in ss)
                    {
                        if (!s.Equals(id))
                        {
                            tempStr += s + ";";
                        }
                    }

                    string csId = row["Id"].ToString();
                    CaseStudyInfo info = CaseStudyDLL.GetInfo(csId);
                    info.Technology = tempStr;
                    CaseStudyDLL.Update(info);
                }
            }

            return TechnologyDLL.Delete(id);
        }
    }
}
